#include <iostream>
#include <cassert>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

#define MAX_SIZE 1024

using namespace std;

int main()
{
    //1.创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n == 0);
    (void)n;  //防止告警
    cout << "pipefd[0]" << pipefd[0] << "," << "pipefd[1]" << pipefd[1] << endl;

    //2.创建子进程
    pid_t id = fork();

    if(id < 0)
    {
        perror("fork");
        return 1;
    }

    //子写，父读
    //3.父子关闭不需要的fd，形成单通道通信
    if(id == 0)
    {
        //child
        close(pipefd[0]);
        //关闭读，保留写
        int cnt = 10;
        while(cnt--)
        {
            char message[MAX_SIZE];
            snprintf(message, sizeof(message), "I am child, my id: %d, %d",getpid(),cnt);
            //通过管道共享信息
            write(pipefd[1], message, strlen(message));
            sleep(1);
        }
        cout << "child close w piont" << endl;
        exit(0);
    }

    //father
    close(pipefd[1]);
    //关闭写，保留读
    char buffer[MAX_SIZE];
    //读取通过管道的信息
    while(true)
    {
        ssize_t pos = read(pipefd[0], buffer, sizeof(buffer)-1);
        if(pos > 0)
        {
            buffer[pos] = '\0';
            cout << "I am your father:" << getpid() << "child say :" << buffer << endl; 
        }
        else if(pos == 0)
        {
            cout << "child quit, me to!" << endl;
            break;
        }
        else cout << "father return val(n): " << n << endl;
        sleep(1);
        break;
        
        close(pipefd[0]);
    }

    //等待子进程
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid == id)
    {
        cout << "wait success! child exit sig:" << (status&0x7F) <<endl;
    }

    return 0;
}
